<template>
  <div class="enhanced-loadout-card" :class="{ 'over-budget': !loadout.within_target }">
    <!-- 卡片头部 -->
    <div class="card-header">
      <div class="header-left">
        <div class="budget-status">
          <n-icon :size="16" :color="budgetStatusColor">
            <component :is="budgetStatusIcon" />
          </n-icon>
          <span class="status-text">{{ budgetStatusText }}</span>
        </div>
        <div class="style-tag">
          <n-tag :type="styleTagType" size="small" round>
            {{ loadout.style }}
          </n-tag>
        </div>
      </div>
      <div class="header-right">
        <div class="total-cost">
          <span class="cost-label">总成本</span>
          <span class="cost-value">{{ formatPrice(loadout.total_cost) }}</span>
        </div>
        <div class="budget-ratio">
          <n-progress
            type="circle"
            :percentage="Math.round(loadout.budget_ratio * 100)"
            :color="budgetProgressColor"
            :size="40"
            :stroke-width="4"
          />
        </div>
      </div>
    </div>

    <!-- 装备展示区域 -->
    <div class="equipment-showcase">
      <!-- 主武器 -->
      <div v-if="weaponData" class="main-weapon">
        <div class="weapon-card">
          <div class="equipment-image-container">
            <n-image
              :src="weaponData.pic"
              :alt="weaponData.object_name"
              width="80"
              height="80"
              object-fit="contain"
              :fallback-src="'/images/weapon-placeholder.png'"
              class="equipment-image"
            />
            <div class="grade-badge weapon-grade">{{ weaponData.grade }}</div>
          </div>
          <div class="weapon-info">
            <h4 class="weapon-name">{{ weaponData.object_name }}</h4>
            <div class="weapon-details">
              <n-space :size="8">
                <n-tag size="tiny" type="info">{{ weaponData.second_class_cn }}</n-tag>
                <n-tag size="tiny" type="default">{{ weaponData.weight }}kg</n-tag>
                <n-tag size="tiny" type="default">{{ weaponData.length }}×{{ weaponData.width }}</n-tag>
              </n-space>
            </div>
            <div class="price-info">
              <span class="current-price">{{ formatPrice(weaponData.current_price) }}</span>
              <span class="price-change" :class="getPriceChangeClass(weaponData.price_change_percent)">
                {{ formatPriceChange(weaponData.price_change_percent) }}
              </span>
            </div>
          </div>
        </div>
      </div>

      <!-- 配件区域 -->
      <div v-if="accessoriesData.length > 0" class="accessories-section">
        <h5 class="section-title">
          <n-icon :size="14"><AttachOutline /></n-icon>
          配件装备
        </h5>
        <div class="accessories-grid">
          <div v-for="(accessory, index) in accessoriesData" :key="index" class="accessory-item">
            <div class="accessory-image-container">
              <n-image
                :src="accessory.pic"
                :alt="accessory.object_name"
                width="50"
                height="50"
                object-fit="contain"
                :fallback-src="'/images/accessory-placeholder.png'"
                class="accessory-image"
              />
              <div class="grade-badge accessory-grade">{{ accessory.grade }}</div>
            </div>
            <div class="accessory-info">
              <div class="accessory-name">{{ accessory.object_name }}</div>
              <div class="accessory-price">{{ formatPrice(accessory.current_price) }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 防护装备区域 -->
      <div v-if="hasProtectionEquipment" class="protection-section">
        <h5 class="section-title">
          <n-icon :size="14"><ShieldOutline /></n-icon>
          防护装备
        </h5>
        <div class="protection-grid">
          <!-- 头盔 -->
          <div v-if="helmetData" class="protection-item">
            <div class="protection-image-container">
              <n-image
                :src="helmetData.pic"
                :alt="helmetData.object_name"
                width="45"
                height="45"
                object-fit="contain"
                :fallback-src="'/images/helmet-placeholder.png'"
                class="protection-image"
              />
              <div class="grade-badge protection-grade">{{ helmetData.grade }}</div>
            </div>
            <div class="protection-info">
              <div class="protection-type">头盔</div>
              <div class="protection-name">{{ helmetData.object_name }}</div>
              <div class="protection-price">{{ formatPrice(helmetData.current_price) }}</div>
            </div>
          </div>

          <!-- 护甲 -->
          <div v-if="armorData" class="protection-item">
            <div class="protection-image-container">
              <n-image
                :src="armorData.pic"
                :alt="armorData.object_name"
                width="45"
                height="45"
                object-fit="contain"
                :fallback-src="'/images/armor-placeholder.png'"
                class="protection-image"
              />
              <div class="grade-badge protection-grade">{{ armorData.grade }}</div>
            </div>
            <div class="protection-info">
              <div class="protection-type">护甲</div>
              <div class="protection-name">{{ armorData.object_name }}</div>
              <div class="protection-price">{{ formatPrice(armorData.current_price) }}</div>
            </div>
          </div>

          <!-- 背包 -->
          <div v-if="backpackData" class="protection-item">
            <div class="protection-image-container">
              <n-image
                :src="backpackData.pic"
                :alt="backpackData.object_name"
                width="45"
                height="45"
                object-fit="contain"
                :fallback-src="'/images/backpack-placeholder.png'"
                class="protection-image"
              />
              <div class="grade-badge protection-grade">{{ backpackData.grade }}</div>
            </div>
            <div class="protection-info">
              <div class="protection-type">背包</div>
              <div class="protection-name">{{ backpackData.object_name }}</div>
              <div class="protection-price">{{ formatPrice(backpackData.current_price) }}</div>
            </div>
          </div>

          <!-- 胸挂 -->
          <div v-if="chestRigData" class="protection-item">
            <div class="protection-image-container">
              <n-image
                :src="chestRigData.pic"
                :alt="chestRigData.object_name"
                width="45"
                height="45"
                object-fit="contain"
                :fallback-src="'/images/chest-rig-placeholder.png'"
                class="protection-image"
              />
              <div class="grade-badge protection-grade">{{ chestRigData.grade }}</div>
            </div>
            <div class="protection-info">
              <div class="protection-type">胸挂</div>
              <div class="protection-name">{{ chestRigData.object_name }}</div>
              <div class="protection-price">{{ formatPrice(chestRigData.current_price) }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 卡片底部统计 -->
    <div class="card-footer">
      <div class="stats-row">
        <div class="stat-item">
          <span class="stat-label">武器</span>
          <span class="stat-value">{{ formatPrice(weaponData?.current_price || 0) }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">配件</span>
          <span class="stat-value">{{ formatPrice(accessoriesValue) }}</span>
        </div>
        <div class="stat-item">
          <span class="stat-label">防护</span>
          <span class="stat-value">{{ formatPrice(protectionValue) }}</span>
        </div>
        <div class="stat-item total-stat">
          <span class="stat-label">总计</span>
          <span class="stat-value">{{ formatPrice(loadout.total_cost) }}</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed } from 'vue'
import { CheckmarkCircleOutline, WarningOutline, AttachOutline, ShieldOutline } from '@vicons/ionicons5'
import type { TacticalLoadout, TacticalItem } from '@/types/tactical'

interface Props {
  loadout: TacticalLoadout
  index: number
}

const props = defineProps<Props>()

// 数据解析函数
const parseItemData = (itemArray: [string, string, number] | null): TacticalItem | null => {
  if (!itemArray || !Array.isArray(itemArray) || itemArray.length < 3) return null
  
  try {
    const itemInfoStr = itemArray[0]
    const priceDataStr = itemArray[1]
    const avgPrice = itemArray[2]
    
    if (!itemInfoStr || !priceDataStr) return null
    
    // 使用正则表达式提取信息
    const nameMatch = itemInfoStr.match(/object_name='([^']+)'/)
    const objectIdMatch = itemInfoStr.match(/object_id=(\d+)/)
    const gradeMatch = itemInfoStr.match(/grade=(\d+)/)
    const picMatch = itemInfoStr.match(/pic='([^']*)'/)
    const descMatch = itemInfoStr.match(/desc='([^']*)'/)
    const categoryMatch = itemInfoStr.match(/category_id=(\d+)/)
    const weightMatch = itemInfoStr.match(/weight=([\d.]+)/)
    const lengthMatch = itemInfoStr.match(/length=(\d+)/)
    const widthMatch = itemInfoStr.match(/width=(\d+)/)
    const primaryClassMatch = itemInfoStr.match(/primary_class='([^']*)'/)
    const secondClassMatch = itemInfoStr.match(/second_class_cn='([^']*)'/)
    
    // 解析价格数据
    const currentPriceMatch = priceDataStr.match(/current_price=([\d.]+)/)
    const price24hAgoMatch = priceDataStr.match(/price_24h_ago=([\d.]+)/)
    const priceChangeMatch = priceDataStr.match(/price_change_24h=([-\d.]+)/)
    const priceChangePercentMatch = priceDataStr.match(/price_change_percent=([-\d.]+)/)
    
    return {
      object_id: objectIdMatch ? parseInt(objectIdMatch[1]) : 0,
      object_name: nameMatch ? nameMatch[1] : '未知装备',
      category_id: categoryMatch ? parseInt(categoryMatch[1]) : 0,
      grade: gradeMatch ? parseInt(gradeMatch[1]) : 1,
      pic: picMatch ? picMatch[1] : '',
      current_price: currentPriceMatch ? parseFloat(currentPriceMatch[1]) : avgPrice || 0,
      price_24h_ago: price24hAgoMatch ? parseFloat(price24hAgoMatch[1]) : 0,
      price_change_24h: priceChangeMatch ? parseFloat(priceChangeMatch[1]) : 0,
      price_change_percent: priceChangePercentMatch ? parseFloat(priceChangePercentMatch[1]) : 0,
      has_price_data: true,
      primary_class: primaryClassMatch ? primaryClassMatch[1] : '',
      second_class_cn: secondClassMatch ? secondClassMatch[1] : '',
      desc: descMatch ? descMatch[1] : '',
      weight: weightMatch ? parseFloat(weightMatch[1]) : 0,
      length: lengthMatch ? parseInt(lengthMatch[1]) : 1,
      width: widthMatch ? parseInt(widthMatch[1]) : 1
    }
  } catch (error) {
    console.error('解析装备数据失败:', error, itemArray)
    return null
  }
}

// 计算属性
const weaponData = computed(() => parseItemData(props.loadout.weapon))
const accessoriesData = computed(() => {
  if (!props.loadout.accessories || !Array.isArray(props.loadout.accessories)) return []
  return props.loadout.accessories
    ?.map(acc => parseItemData(acc))
    .filter(Boolean) as TacticalItem[] || []
})
const helmetData = computed(() => parseItemData(props.loadout.helmet))
const armorData = computed(() => parseItemData(props.loadout.armor))
const backpackData = computed(() => parseItemData(props.loadout.backpack))
const chestRigData = computed(() => parseItemData(props.loadout.chest_rig))

const accessoriesValue = computed(() => {
  return accessoriesData.value.reduce((total, accessory) => {
    return total + (accessory.current_price || 0)
  }, 0)
})

const protectionValue = computed(() => {
  let total = 0
  if (helmetData.value) total += helmetData.value.current_price || 0
  if (armorData.value) total += armorData.value.current_price || 0
  if (backpackData.value) total += backpackData.value.current_price || 0
  if (chestRigData.value) total += chestRigData.value.current_price || 0
  return total
})

const hasProtectionEquipment = computed(() => {
  return helmetData.value || armorData.value || backpackData.value || chestRigData.value
})

// 预算状态
const budgetStatusText = computed(() => {
  return props.loadout.within_target ? '预算内' : '超预算'
})

const budgetStatusColor = computed(() => {
  return props.loadout.within_target ? '#52c41a' : '#ff4d4f'
})

const budgetStatusIcon = computed(() => {
  return props.loadout.within_target ? CheckmarkCircleOutline : WarningOutline
})

const budgetProgressColor = computed(() => {
  const ratio = props.loadout.budget_ratio || 0
  if (ratio <= 0.8) return '#52c41a'
  if (ratio <= 1.0) return '#faad14'
  return '#ff4d4f'
})

const styleTagType = computed(() => {
  const style = (props.loadout.style || '').toLowerCase()
  if (style.includes('进攻') || style.includes('攻击')) return 'error'
  if (style.includes('防守') || style.includes('防御')) return 'info'
  if (style.includes('平衡') || style.includes('均衡')) return 'success'
  return 'default'
})

// 格式化函数
const formatPrice = (price: number | undefined) => {
  return (price || 0).toLocaleString('zh-CN')
}

const formatPriceChange = (percent: number | undefined) => {
  const value = percent || 0
  if (value > 0) return `+${value.toFixed(1)}%`
  if (value < 0) return `${value.toFixed(1)}%`
  return '0%'
}

const getPriceChangeClass = (percent: number | undefined) => {
  const value = percent || 0
  if (value > 0) return 'price-up'
  if (value < 0) return 'price-down'
  return 'price-same'
}
</script>

<style scoped>
.enhanced-loadout-card {
  background: var(--n-card-color);
  border-radius: 16px;
  border: 1px solid var(--n-border-color);
  overflow: hidden;
  transition: all 0.3s ease;
  position: relative;
}

.enhanced-loadout-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  border-color: var(--n-primary-color);
}

.enhanced-loadout-card.over-budget {
  border-color: rgba(255, 77, 79, 0.3);
  background: linear-gradient(135deg, rgba(255, 77, 79, 0.02) 0%, var(--n-card-color) 100%);
}

/* 卡片头部 */
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: linear-gradient(135deg, var(--n-primary-color-hover) 0%, var(--n-card-color) 100%);
  border-bottom: 1px solid var(--n-border-color);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.budget-status {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.total-cost {
  text-align: right;
}

.cost-label {
  display: block;
  font-size: 12px;
  color: var(--n-text-color-3);
  margin-bottom: 4px;
}

.cost-value {
  font-size: 18px;
  font-weight: 700;
  color: var(--n-primary-color);
}

/* 装备展示区域 */
.equipment-showcase {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 主武器 */
.main-weapon {
  position: relative;
}

.weapon-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: linear-gradient(135deg, rgba(255, 107, 53, 0.1) 0%, transparent 100%);
  border-radius: 12px;
  border: 1px solid rgba(255, 107, 53, 0.2);
}

.equipment-image-container {
  position: relative;
  flex-shrink: 0;
}

.equipment-image {
  border-radius: 8px;
}

.grade-badge {
  position: absolute;
  top: -4px;
  right: -4px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
  font-weight: bold;
  color: white;
  border: 2px solid var(--n-card-color);
}

.weapon-grade {
  background: linear-gradient(135deg, #ff6b35 0%, #f7931e 100%);
}

.accessory-grade {
  background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
}

.protection-grade {
  background: linear-gradient(135deg, #45b7d1 0%, #96c93d 100%);
}

.weapon-info {
  flex: 1;
}

.weapon-name {
  margin: 0 0 8px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--n-text-color-1);
}

.weapon-details {
  margin-bottom: 8px;
}

.price-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.current-price {
  font-size: 16px;
  font-weight: 600;
  color: var(--n-primary-color);
}

.price-change {
  font-size: 12px;
  font-weight: 500;
}

.price-up {
  color: var(--n-error-color);
}

.price-down {
  color: var(--n-success-color);
}

.price-same {
  color: var(--n-text-color-3);
}

/* 配件区域 */
.accessories-section,
.protection-section {
  border-top: 1px solid var(--n-border-color);
  padding-top: 16px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 12px 0;
  font-size: 14px;
  font-weight: 600;
  color: var(--n-text-color-2);
}

.accessories-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 12px;
}

.accessory-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px;
  background: var(--n-fill-color);
  border-radius: 8px;
  border: 1px solid var(--n-border-color);
}

.accessory-image-container {
  position: relative;
  flex-shrink: 0;
}

.accessory-image {
  border-radius: 4px;
}

.accessory-info {
  flex: 1;
  min-width: 0;
}

.accessory-name {
  font-size: 12px;
  font-weight: 500;
  color: var(--n-text-color-1);
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.accessory-price {
  font-size: 11px;
  color: var(--n-primary-color);
  font-weight: 600;
}

/* 防护装备区域 */
.protection-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
  gap: 12px;
}

.protection-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 12px;
  background: var(--n-fill-color);
  border-radius: 8px;
  border: 1px solid var(--n-border-color);
  text-align: center;
}

.protection-image-container {
  position: relative;
  margin-bottom: 8px;
}

.protection-image {
  border-radius: 4px;
}

.protection-info {
  flex: 1;
  width: 100%;
}

.protection-type {
  font-size: 10px;
  color: var(--n-text-color-3);
  margin-bottom: 4px;
  font-weight: 500;
}

.protection-name {
  font-size: 12px;
  font-weight: 500;
  color: var(--n-text-color-1);
  margin-bottom: 4px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.protection-price {
  font-size: 11px;
  color: var(--n-primary-color);
  font-weight: 600;
}

/* 卡片底部 */
.card-footer {
  padding: 16px 20px;
  background: var(--n-fill-color);
  border-top: 1px solid var(--n-border-color);
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
}

.stat-label {
  font-size: 11px;
  color: var(--n-text-color-3);
  margin-bottom: 4px;
  font-weight: 500;
}

.stat-value {
  font-size: 13px;
  font-weight: 600;
  color: var(--n-text-color-1);
}

.total-stat {
  border-left: 1px solid var(--n-border-color);
  padding-left: 12px;
}

.total-stat .stat-value {
  color: var(--n-primary-color);
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .header-left {
    width: 100%;
    justify-content: space-between;
  }

  .header-right {
    width: 100%;
    justify-content: space-between;
  }

  .weapon-card {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .accessories-grid {
    grid-template-columns: 1fr;
  }

  .protection-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .stats-row {
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
  }
}

@media (max-width: 480px) {
  .equipment-showcase {
    padding: 16px;
  }

  .card-header {
    padding: 16px;
  }

  .card-footer {
    padding: 12px 16px;
  }

  .protection-grid {
    grid-template-columns: 1fr;
  }
}
</style>